from django.http import JsonResponse
from django.shortcuts import render
from django.contrib.admin.views.decorators import staff_member_required
from django.contrib.auth.decorators import login_required
from django.views.decorators.http import require_POST
from app.news.models import NewsTag, News
from utils import restful
from django.views.generic import View
from django.conf import settings
import os
from qiniu import Auth
from .forms import NewsPubForm
# 专门给类视图用的
from django.utils.decorators import method_decorator
from django.core.paginator import Paginator
from utils.hpage import HPage
from datetime import datetime, timedelta
from urllib import parse


# 这个页面 必须是员工才能访问
@staff_member_required(login_url="/auth/login/")
def index(request):
    return render(request, 'admin/index.html')


def news_tag(request):
    # tags = NewsTag.objects.filter(is_delete=True).all()
    tags = NewsTag.objects.all()
    return render(request, 'admin/news/new_tags.html', context={"tags": tags})


# 只有post 请求 才能通过
# 添加
@require_POST
def add_news_tag(request):
    tag_name = request.POST.get("name")
    print(tag_name)
    # 当你要添加的时候 判断一下数据库是不是已经有这个标签
    tag = NewsTag.objects.filter(name=tag_name).first()
    if tag:
        return restful.params_error(message="改标签存在")
    tag = NewsTag.objects.create(name=tag_name)
    # 怎么把queryset变成 json数据  serializer
    # return restful.ok()  # ok() 不能传参数 == result() 可以传参数
    news_count = tag.news.count()
    return restful.result(data={"tag_id": tag.id, "tag_name": tag.name, "news_count": news_count})


# 编辑
@require_POST
def edit_news_tag(request):
    # 获取前端的值 id = 4
    tag_id = request.POST.get("id")
    name = request.POST.get("name")
    # id =4 第一条数据 querySet对象  first() get() .delete() .update()
    tag = NewsTag.objects.filter(id=tag_id)
    if tag:
        tag.update(name=name)
        return restful.ok()
    return restful.params_error(message="标签不存在")


# 删除
@require_POST
def del_news_tag(request):
    tag_id = request.POST.get("id")
    tag = NewsTag.objects.filter(id=tag_id)
    if tag:
        # 真删
        tag.delete()
        # 假删
        # tag.update(is_delete=False)
        return restful.ok()
    return restful.params_error(message="标签不存在")


# get/post get返回发布新闻的页面 post 提交数据 login_required
@method_decorator(login_required, name="dispatch")
class NewsPub(View):

    def get(self, request):
        tags = NewsTag.objects.all()
        return render(request, 'admin/news/news_pub.html', context={"tags": tags})

    def post(self, request):
        form = NewsPubForm(request.POST)
        if form.is_valid():
            # cleaned_data
            get_data = form.cleaned_data
            title = get_data.get("title")
            desc = get_data.get("desc")
            tag_id = get_data.get("tag_id")
            tag = NewsTag.objects.get(id=tag_id)
            thumbnail_url = get_data.get('thumbnail_url')
            content = get_data.get('content')
            news = News.objects.create(title=title, desc=desc, thumbnail_url=thumbnail_url, tag=tag, content=content,
                                       author=request.user)
            return restful.result(data={"news_id": news.id})
        # 返回了错误 这个错误是一定会出现在 success 并不会出现在 error
        return restful.params_error(message=form.get_error())


class NewsList(View):
    def get(self, request):
        # ?p=5
        p = int(request.GET.get("p", 1))
        # 是不是 字符串 'None' ？ True : False
        start_time = request.GET.get("start_time", '')
        end_time = request.GET.get("end_time", '')
        title = request.GET.get("title", '')
        author = request.GET.get("author", '')
        tag_id = int(request.GET.get("tag_id", 0))

        tags = NewsTag.objects.all()
        newses = News.objects.defer('content').select_related('tag', 'author')
        if start_time and end_time:
            start_date = datetime.strptime(start_time, '%Y/%m/%d')
            end_date = datetime.strptime(end_time, '%Y/%m/%d') + timedelta(days=1)
            # 包上一层 自带的
            from django.utils.timezone import make_aware
            newses = newses.filter(pub_time__range=(make_aware(start_date), make_aware(end_date)))

        if title:
            # 12345A ==> a
            newses = newses.filter(title__icontains=title)

        if author:
            newses = newses.filter(author__username__icontains=author)

        if tag_id:
            newses = newses.filter(tag=tag_id)
        paginator = Paginator(newses, settings.ONE_PAGE_NEWS_COUNT)
        # print('---------')
        # # for i in range(1, 31): 表示30
        # print(p.page_range)
        # print(p.num_pages)
        # print(p.count)
        # print('---------')
        # 返回一个  Page 对象
        page = paginator.page(p)
        # print('=============')
        # print(page.object_list)
        # print(page.start_index())
        # print(page.end_index())
        # print(page.number)
        # print('=============')
        ret = HPage.get_page(paginator, page)
        context = {
            "tags": tags,
            "newses": page.object_list,
            "paginator": paginator,
            "page": page,
            "start_time": start_time,
            "end_time": end_time,
            "title": title,
            "author": author,
            "tag_id": tag_id,
            "other_param": parse.urlencode({
                "start_time": start_time,
                "end_time": end_time,
                "title": title,
                "author": author,
                "tag_id": tag_id,
            })
        }
        context.update(ret)
        print(context)
        return render(request, 'admin/news/news_list.html', context=context)


# 上传文件的视图
def upload_file(request):
    # 获取到图片  request.FILES  request.GET
    file = request.FILES.get('uploadFile')
    # 获取文件的名字
    file_name = file.name
    # 定义文件的路径 # xx/xx/djPro/media/python.png /home/pyvip/djCourse/djPro/media
    file_path = os.path.join(settings.MEDIA_ROOT, file_name)
    with open(file_path, 'wb') as f:
        # 如果你的小视频 chunks 最后是不是返回一个 生成器
        # 如果你传的是小视频 会分段读取 具有优化  针对大文件
        for chunk in file.chunks():
            f.write(chunk)
    # 生成 url 地址 http://192.168.31.200:8000/media/python.png
    # 动态获取 http://192.168.31.200:8000/
    # print(request.build_absolute_uri(settings.MEDIA_URL+ file_name))
    file_url = request.build_absolute_uri(settings.MEDIA_URL + file_name)
    return restful.result(data={"url": file_url})


def up_token(request):
    # 需要填写你的 Access Key 和 Secret Key
    access_key = settings.QI_NIU_ACCESS_KEY
    secret_key = settings.QI_NIU_SECRET_KEY
    # 构建鉴权对象
    q = Auth(access_key, secret_key)
    # 要上传的空间
    bucket_name = settings.QI_NIU_BUCKET_NAME
    # 生成上传 Token，可以指定过期时间等
    # 3600为token过期时间，秒为单位。3600等于一小时
    token = q.upload_token(bucket_name, expires=3600)
    print(token)
    return JsonResponse({"uptoken": token})
